<?php
/**
 * @file
 * Retrieves deeds from the database and displays them in a table.
 *
 * The filter details are retreived from the POST request.
 *
 * Usage:
 *  A page that wants to display deeds in a table should include/require this
 *  page (once).
 *
 * GET Parameter(s):
 *  - See 'js_params_get.php'.
 *
 * POST Parameter(s):
 *  - {NAME_FILTER_FIELD_MASK}   : Filter mask.
 *  - {NAME_FILTER_FIELD_ROWSPP} : Number of rows per page.
 *
 * Global variable(s) set:
 *  - None.
 *
 * Global variable(s) unset:
 *  - None.
 *
 * Exception(s):
 *  - None.
 *
 * This file includes/requires:
 *  - h_greenindeed.php
 *  - h_deed.php
 *  - h_filter.php
 *  - h_jqui.php
 *  - util.php
 *  - deed_view_ids_div_msg.php
 *  - div_msg.php
 *  - fb_user_uid.php
 *  - db_mysql_greenindeed.php
 *  - db_mysql_connect.php
 *  - db_mysql_disconnect.php
 *  - exception_msg.php
 */

// header file(s) ==============================================================
require_once "h_greenindeed.php";
require_once "h_deed.php";
require_once "h_filter.php";
require_once $PATH_COMMON . "php/h_jqui.php";
require_once $PATH_COMMON . "php/util.php";


// implementation ==============================================================
// message div
?>
<?php
try {
  // create facebook object and retreive facebook user id
  require_once $PATH_COMMON . "php/fb_user_uid.php";

  // must call facebook function before output div to get around 'Cannot modify
  //header information ...' problem
?>
<?php require_once "deed_view_ids_div_msg.php" ?>
<?php require "div_msg.php" ?>
<?php
  // get filter mask
  if (false == isset($_POST[NAME_FILTER_FIELD_MASK])) {
    // filter not found in post request
    throw new Exception(MSG_REQUEST_INVALID);
  }
  $filter = $_POST[NAME_FILTER_FIELD_MASK];

  // get user ids and set sql 'where' condition
  $ids_user            = array();
  $sql_condition_where = "and D.LOCALE = '" . $locale_user . "' ";
  if (0 != (VAL_FILTER_WORLD & $filter)) {
    // get deeds of the world

    // get excluded ids
    if (0 == (VAL_FILTER_YOURSELF & $filter)) {
      // exclude current user
      $ids_user[] = $fb_uid;
    }
    if (0 == (VAL_FILTER_FRIENDS & $filter)) {
      // exclude friends of current user
      $ids_user = array_merge($ids_user, $fb->api_client->friends_get());
    }
    if (0 != count($ids_user)) {
      // exclude at least one user
      $sql_condition_where .= "and D.USER_ID not in ("
                           . implode(",", $ids_user) . ")";
    }
  } else {
    // get deeds of current user and/or friends of current user

    // ensure at least one id (assume no negative id)
    $ids_user[] = "-1";
    // get deeds of current user and/or friends of current user
    if (0 != (VAL_FILTER_YOURSELF & $filter)) {
      // include current user
      $ids_user[] = $fb_uid;
    }
    if (0 != (VAL_FILTER_FRIENDS & $filter)) {
      // include friends of current user
      $ids_user = array_merge($ids_user, $fb->api_client->friends_get());
    }
    // include at least one user
    $sql_condition_where .= "and D.USER_ID in ("
                         . implode(",", $ids_user) . ")";
  }

  // get page number
  $offset = DEF_OFFSET; // TODO: real pagination
  $limit  = $offset
          + (true == isset($_POST[NAME_FILTER_FIELD_ROWSPP]))
          ? $_POST[NAME_FILTER_FIELD_ROWSPP]
          : DEF_LIMIT;

  // connect to database
  require "db_mysql_greenindeed.php";
  require $PATH_COMMON . "php/db_mysql_connect.php";

  // get deeds
  $deeds = mysql_query(
    "select
       *,
       date_format(D.DEED_DATETIME, '%d %b %Y %l:%i%p, %W') as DEED_DATETIME
     from     DEEDS D, TYPES_DEED TD
     where    D.DEED_TYPE_ID = TD.DEED_TYPE_ID " . $sql_condition_where . "
     order by D.DEED_DATETIME desc
     limit    " . $offset . "," . $limit
  );
  $sql_error = mysql_error();

  // disconnect from database
  require $PATH_COMMON . "php/db_mysql_disconnect.php";

  // check result
  if (false == $deeds) {
    // error executing query
    throw new Exception($sql_error);
  }
  // show result
  if (0 == mysql_num_rows($deeds)) {
    // no deed found
?>
<?php echo LBL_NO_DEED ?>
<?php
  } else {
    // show deeds in table
?>
<table width="100%">
  <?php
    $users_info = array();
    $user_info  = null;
    while ($deed = mysql_fetch_array($deeds)) {
      // retreive deed statement
      $deed_statement         = $deed["DEED_STATEMENT"];
      $deed_statement_search  =
        explode(DELIMITER_DEED_STATEMENT, $deed["DEED_STATEMENT_SEARCH"]);
      $deed_statement_replace =
        explode(DELIMITER_DEED_STATEMENT, $deed["DEED_STATEMENT_REPLACE"]);

      // get user info
      if (false == isset($users_info[$deed["USER_ID"]])) {
        // get user info from facebook
        // TODO: Get all user info once using a list of uids and access here
        //       rather than calling Facebook for each user.
        $user_info = $fb->api_client->users_getInfo(
          $deed["USER_ID"], "profile_url, pic_square, name"
        );
        $users_info[$deed["USER_ID"]] = $user_info;
      } else {
        // user info already retreived
        $user_info = $users_info[$deed["USER_ID"]];
      }

      // clear previous user info
      unset($html_user_info_replace);
      // profile url
      if (0 == strlen($user_info[0]["profile_url"])) {
        // profile url is private
        $html_user_info_replace[0] = "";
        $html_user_info_replace[1] = "";
      } else {
        // profile url available
        $html_user_info_replace[0] = str_replace(
          HTML_LINK_SEARCH, $user_info[0]["profile_url"], HTML_LINK_OP
        );
        $html_user_info_replace[1] = HTML_LINK_CL;
      }
      // thumbnail image
      $html_user_info_replace[2] = (0 == strlen($user_info[0]["pic_square"]))
                                 ? IMG_THUMBNAIL_SILHOUETTE
                                 : $user_info[0]["pic_square"];
      // user name
      $is_self = false;
      if ($fb_uid == $deed["USER_ID"]) {
        // current user
        $html_user_info_replace[3] = LBL_NAME_YOU;
        $is_self = true;
      } else {
        // other users
        $html_user_info_replace[3] = (0 == strlen($user_info[0]["name"]))
                                   ? LBL_NAME_PRIVATE
                                   : $user_info[0]["name"];
      }

      // add user info (always first item in statement)
      $html_user_info = str_replace(
        $HTML_USER_INFO_SEARCH, $html_user_info_replace, HTML_USER_INFO
      );
      array_unshift($deed_statement_replace, $html_user_info);
      // form statement
      $deed_statement = util_makeClickable(str_replace(
        $deed_statement_search, $deed_statement_replace, $deed_statement
      ));
  ?>
  <tr id="<?php echo ID_VIEW_TR_PREFIX . $deed["DEED_ID"] ?>">
    <td width="70%" style="word-wrap:break-word;">
      <?php // green deed ?>
      <?php echo $deed_statement ?>
    </td>
    <td width="29%">
      <?php // green deed date and time ?>
      <?php echo $deed["DEED_DATETIME"]; ?>
    </td>
    <td width="1%">
      <?php if (true == $is_self) { ?>
      <?php // 'delete' button ?>
      <a href="#"
         class="<?php echo CSS_CLASS_BUTTON_DELETE . " "
                           . JQUI_CSS_CLASS_ICON ?>"
         id="<?php echo $deed["DEED_ID"] ?>"
         title="<?php echo LBL_DEED_DELETE?>"
      >
        <span class="ui-icon ui-icon-trash"></span>
      </a>
      <?php } else { ?>
      <?php // can't delete other people's deed ?>
      &nbsp;
      <?php } ?>
    </td>
  </tr>
  <?php
    }
  ?>
</table>
<?php // delete deed confirmation message ?>
<div id="dialog"
     title="<?php echo LBL_DEL_CONFIRM_TITLE ?>"
     style="display:none">
  <p><?php echo LBL_DEL_CONFIRM_TEXT ?></p>
</div>
<?php
  }
} catch (Exception $ex) {
  // show exception message
  require $PATH_COMMON . "php/exception_msg.php";
}
?>
